package com.example.Aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Description TODO
 * @Date 2024/5/15 23:54
 * @Created by houjunfeng
 */
@Aspect
public class Proxy {

    @Pointcut("execution(* com.example.Aop.Target.*(..))")
    public void pointCunt(){
    }
    @Before("pointCunt()")
    public void before(JoinPoint jpt){
        //String name =jpt.getSignature().getName();方法名
        Object[] args = jpt.getArgs();//参数表
        System.out.println("执行前方法"+"方法名:"+jpt.getSignature().getName()+"......."+"参数表:"+jpt.getArgs().getClass().getTypeName());

        //参数值
        Object[] arguments = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            arguments[i] = args[i];
        }
        String paramter = "";
        if (arguments != null) {
            try {
                paramter = JSONObject.toJSONString(arguments);
            } catch (Exception e) {
                paramter = arguments.toString();
            }
            System.out.println("参数值："+paramter);
        }

        System.out.println("----------Before开始-----------");

        System.out.println("方法名："+ jpt.getSignature().getName());
        System.out.println("参数值集合："+ Arrays.asList(jpt.getArgs()));
        System.out.println("参数值类型："+ jpt.getArgs()[0].getClass().getTypeName()+"   "+jpt.getArgs()[1].getClass().getTypeName());
        //获取目标注解对象，CacheableTest是自定义的一个注解
        CacheableTest cacheable = ((MethodSignature)jpt.getSignature()).getMethod().getAnnotation(CacheableTest.class);
        String classType = jpt.getTarget().getClass().getName();
        System.out.println("目标注解对象："+ cacheable);
        System.out.println("获取目标方法所在类："+ classType);

        System.out.println("----------Before结束-----------");
    }

    @After("pointCunt()")
    public void after(){
        System.out.println("执行后方法");
    }

    @AfterReturning(value = "pointCunt()",returning = "obj")
    public void returnProxy(Object obj){
        System.out.println("返回方法"+"----返回值："+obj);
    }

    @AfterThrowing(value = "pointCunt()",throwing = "exception")
    public void exception(Exception exception){
        System.out.println("异常方法"+"---->异常："+exception);
    }
}
